//
//  HDPlayerView.m
//  HDYanBianCity
//
//  Created by 牛的mini on 12/18/15.
//  Copyright © 2015 牛的mini. All rights reserved.
//

#import "HDPlayerView.h"
#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/MediaPlayer.h>

typedef enum{
    kPlay_Status_Unknown,
    kPlay_Status_Playing,
    kPlay_Status_Pause,
    kPlay_Status_Stop,
}playStatus;

@interface HDPlayerView()
{
    BOOL       enterBgPlaying;
    HDMapObj   *audioRes;
    playStatus playerStatus;
    CGFloat    currentTime;
}
@property (strong, nonatomic) id       timeObserver;
@property (strong, nonatomic) AVPlayer *audioPlayer;
@property (nonatomic, assign) double   totalDuration;


- (IBAction)updateCurrentTime:(UISlider *)sender;
- (IBAction)audioControlAction:(UIButton *)sender;
- (void)updateSliderValue;

@end
@implementation HDPlayerView

#pragma mark
#pragma mark -------- Earphone Methods --------

// 判断耳机拔插事件的
- (void)audioRouteChangeListenerCallback:(NSNotification*)notification {
    NSDictionary *interuptionDict = notification.userInfo;
    NSInteger routeChangeReason = [[interuptionDict valueForKey:AVAudioSessionRouteChangeReasonKey] integerValue];
    switch (routeChangeReason) {
        case AVAudioSessionRouteChangeReasonNewDeviceAvailable:
            LOG(@"AVAudioSessionRouteChangeReasonNewDeviceAvailable");
            LOG(@"耳机插入");
            break;
            
        case AVAudioSessionRouteChangeReasonCategoryChange:            // called at start - also when other audio wants to play
            LOG(@"AVAudioSessionRouteChangeReasonCategoryChange");
            break;
            
        case AVAudioSessionRouteChangeReasonOldDeviceUnavailable:
            dispatch_async(dispatch_get_main_queue(), ^{
                LOG(@"AVAudioSessionRouteChangeReasonOldDeviceUnavailable");
                LOG(@"耳机拔出，停止播放操作");
                [self backToBackground];
            });
            break;
    }
}

#pragma mark
#pragma mark -------- Init Methods --------

- (void)awakeFromNib
{
    [super awakeFromNib];
    [self.audioSlider setThumbImage:[UIImage imageNamed:@"audio_slider_btn"] forState:UIControlStateNormal];
    [_audioSlider addTarget:self action:@selector(sliderTouchEndAction) forControlEvents:UIControlEventTouchUpOutside];

    currentTime = 0;
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(audioRouteChangeListenerCallback:)
                                                 name:AVAudioSessionRouteChangeNotification object:nil];//设置通知
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(backFromBackground)
                                                 name:UIApplicationDidBecomeActiveNotification object:nil];//设置通知
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(backToBackground)
                                                 name:UIApplicationDidEnterBackgroundNotification object:nil];//设置通知
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(audioInterruption)
                                                 name:AVAudioSessionInterruptionNotification object:nil];//设置通知
    
}

- (void)audioInterruption
{
    if (playerStatus == kPlay_Status_Playing)
    {
        [self audioControlAction:nil];
    }
}

- (void)backFromBackground
{
    if (enterBgPlaying == YES)
    {
        [self audioControlAction:nil];
    }
}

- (void)backToBackground
{
    if (playerStatus == kPlay_Status_Playing)
    {
        [self audioControlAction:nil];
        enterBgPlaying = YES;
    }
    else
    {
        enterBgPlaying = NO;
    }
}

#pragma mark
#pragma mark -------- Audio Methods --------

#define Play_Status_Btn_Img_Name  @"audio_play_button"
#define Pause_Status_Btn_Img_Name @"audio_pause_button"

- (void)addTimeObserverToPlayer
{
    if (self.timeObserver)
        return;
    
    double interval = 0.1;
    
    __block __weak HDPlayerView *player = self;
    self.timeObserver = [self.audioPlayer addPeriodicTimeObserverForInterval:CMTimeMakeWithSeconds(interval, NSEC_PER_SEC)
                                                                       queue:dispatch_get_main_queue()
                                                                  usingBlock:^(CMTime time){
                                                                      [player updateSliderValue];
                                                                  }];
}

-(void)updateSliderValue
{
    double duration = CMTimeGetSeconds([self.audioPlayer.currentItem duration]);
    if (duration > 0)
        self.totalDuration = duration;

    if (isfinite(duration))
    {
        double time = CMTimeGetSeconds([self.audioPlayer currentTime]);
        
        [self.audioSlider setValue:time / duration];
        if (time+0.1 >= duration)
        {
            _audioSlider.value = 0.0f;
            [self stopAudio];
            [[NSNotificationCenter defaultCenter] postNotificationName:kPlayer_Play_To_End_Notification object:nil];

            return;
        }
    }
    
    double seconds = CMTimeGetSeconds([self.audioPlayer currentTime]);
    if (isfinite(seconds))
    {
        if (seconds < 0.0)
        {
            seconds = 0.0;
        }
        int secondsInt = round(seconds);
        int minutes = secondsInt/60;
        int minutesOnes = minutes%10;
        int minutesTens = minutes/10;
        secondsInt -= minutes*60;
        int secondsOnes = secondsInt%10;
        int secondsTens = secondsInt/10;
        
        _audioCurrentTimeLabel.text = [NSString stringWithFormat:@"%i%i:%i%i", minutesTens,minutesOnes,secondsTens, secondsOnes];
    }
    
    if (isfinite(duration))
    {
        if (duration < 0.0)
        {
            duration = 0.0;
        }
        int secondsInt = round(duration);
        int minutes = secondsInt/60;
        int minutesOnes = minutes%10;
        int minutesTens = minutes/10;
        secondsInt -= minutes*60;
        int secondsOnes = secondsInt%10;
        int secondsTens = secondsInt/10;
        
        _audioTotalTimeLabel.text = [NSString stringWithFormat:@"%i%i:%i%i", minutesTens,minutesOnes,secondsTens, secondsOnes];
    }
}

- (void)sliderTouchEndAction
{
    if (playerStatus == kPlay_Status_Playing)
    {
        [self.audioPlayer play];
    }
}

- (void)pauseAudioAction
{
    if (playerStatus == kPlay_Status_Playing)
    {
        [self.audioPlayer pause];
        currentTime = CMTimeGetSeconds(_audioPlayer.currentTime);
        playerStatus = kPlay_Status_Pause;
        
        UIImage *audioImg = [UIImage imageNamed:Play_Status_Btn_Img_Name];
        [self.audioControlButton setImage:audioImg forState:UIControlStateNormal];
        [self removeTimeObserverFromPlayer];
    }
}

-(void)stopAudio
{
    [self.audioPlayer pause];
    self.audioPlayer = nil;
    playerStatus = kPlay_Status_Stop;
    [self removeTimeObserverFromPlayer];
    self.audioSlider.value = 0;
    self.audioCurrentTimeLabel.text = @"00:00";
    
    
    UIImage *audioImg = [UIImage imageNamed:Play_Status_Btn_Img_Name];
    [self.audioControlButton setImage:audioImg forState:UIControlStateNormal];

    NSError *error = nil;
    AVAudioSession *audioSessionobj = [AVAudioSession sharedInstance];
    [audioSessionobj setCategory:AVAudioSessionCategoryPlayback error:&error];
}

- (void)removeTimeObserverFromPlayer
{
    if (self.timeObserver)
    {
        [self.audioPlayer removeTimeObserver:self.timeObserver];
        self.timeObserver = nil;
    }
}

-(void)playItem:(HDMapObj *)myRes
{
    if ([audioRes.exhibit_id isEqualToString:myRes.exhibit_id]) {
        if (playerStatus == kPlay_Status_Playing) {
            [self stopAudio];
        }
        else  {
            audioRes = myRes;
            dispatch_queue_t myQueue = dispatch_queue_create("myQueue", nil);
            dispatch_async(myQueue, ^{
                [self playAudio:audioRes.mp3_path];
            });
        }
    }
    else {
        [self stopAudio];
        audioRes = myRes;
        dispatch_async(dispatch_get_main_queue(), ^{
            [self playAudio:audioRes.mp3_path];
        });
    }
}

-(void)playAudio:(NSString *)mp3_path
{
    //playn文件编号（8位）
    NSString *audioPath = mp3_path;
//    audioPath = @"http://47.93.81.30/__video/yqh/mp3/chinese_0001.mp3";
    
    AVPlayerItem * songItem = [[AVPlayerItem alloc]initWithURL:[NSURL URLWithString:audioPath]];
    _audioPlayer = [[AVPlayer alloc]initWithPlayerItem:songItem];
    
    BOOL success = NO;
    NSError *error = nil;
    AVAudioSession *audioSessionobj = [AVAudioSession sharedInstance];
    success = [audioSessionobj setCategory:AVAudioSessionCategoryPlayback error:&error];
    [audioSessionobj setCategory:AVAudioSessionCategoryPlayback error:&error];

    success= [audioSessionobj setActive:true error:&error];
    if (!success)
    {
        NSLog(@"Error setting category: %@", [error localizedDescription]);
        return;
    }
    
    CMTime time = [self.audioPlayer.currentItem duration];
    self.totalDuration = CMTimeGetSeconds(time);
    if (isfinite(_totalDuration))
    {
        if (_totalDuration < 0.0)
        { _totalDuration = 0.0; }
        int secondsInt = round(_totalDuration);
        int minutes = secondsInt/60;
        int minutesOnes = minutes%10;
        int minutesTens = minutes/10;
        secondsInt -= minutes*60;
        int secondsOnes = secondsInt%10;
        int secondsTens = secondsInt/10;
        
        dispatch_async(dispatch_get_main_queue(), ^{
            _audioTotalTimeLabel.text = [NSString stringWithFormat:@"%i%i:%i%i", minutesTens,minutesOnes,secondsTens, secondsOnes];
        });
    }
    
    [self.audioPlayer play];
    playerStatus = kPlay_Status_Playing;
    UIImage *audioImg = [UIImage imageNamed:Pause_Status_Btn_Img_Name];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.audioControlButton setImage:audioImg forState:UIControlStateNormal];
    });
    [self addTimeObserverToPlayer];
}


#pragma mark
#pragma mark -------- Other Methods --------

- (IBAction)updateCurrentTime:(UISlider *)sender
{
    dispatch_async(dispatch_get_main_queue(), ^{
        if (self.audioSlider.value >= 1.0)
        {
            [self stopAudio];
            sender.value = 0.0f;
            [self.audioControlButton setImage:[UIImage imageNamed:Play_Status_Btn_Img_Name] forState:UIControlStateNormal];
            playerStatus = kPlay_Status_Stop;
            [self removeTimeObserverFromPlayer];
            
            return;
        }
        double duration = _totalDuration;
        if (playerStatus == kPlay_Status_Pause || playerStatus == kPlay_Status_Stop)
        {
            currentTime = _totalDuration*_audioSlider.value;
            int secondsInt = round(currentTime);
            int minutes = secondsInt/60;
            int minutesOnes = minutes%10;
            int minutesTens = minutes/10;
            secondsInt -= minutes*60;
            int secondsOnes = secondsInt%10;
            int secondsTens = secondsInt/10;
            
            _audioCurrentTimeLabel.text = [NSString stringWithFormat:@"%i%i:%i%i", minutesTens,minutesOnes,secondsTens, secondsOnes];
        }
        else if (playerStatus == kPlay_Status_Playing)
        {
            if (isfinite(duration))
            {
                float value = [sender value];
                double time = duration*value;
                [self removeTimeObserverFromPlayer];
                float  _playRateToRestore = [self.audioPlayer rate];
                [self.audioPlayer setRate:0.0];
                [self.audioPlayer seekToTime:CMTimeMakeWithSeconds(time, NSEC_PER_SEC)];
                [self.audioPlayer setRate:_playRateToRestore];
                [self addTimeObserverToPlayer];
            }
        }
    });
}

- (IBAction)audioControlAction:(UIButton *)sender
{
    if (self.audioPlayer == nil)
    {
        [self playItem:audioRes];
        return;
    }
    if (playerStatus == kPlay_Status_Playing)
    {
        [self.audioPlayer pause];
        currentTime = CMTimeGetSeconds(_audioPlayer.currentTime);
        playerStatus = kPlay_Status_Pause;
        
        UIImage *audioImg = [UIImage imageNamed:Play_Status_Btn_Img_Name];
        
        [self.audioControlButton setImage:audioImg forState:UIControlStateNormal];
        [self removeTimeObserverFromPlayer];
    }
    else
    {
        [self.audioPlayer seekToTime:CMTimeMakeWithSeconds(currentTime, NSEC_PER_SEC)];
        [self.audioPlayer play];
        playerStatus = kPlay_Status_Playing;
        UIImage *audioImg = [UIImage imageNamed:Pause_Status_Btn_Img_Name];
        
        [self.audioControlButton setImage:audioImg forState:UIControlStateNormal];
        [self addTimeObserverToPlayer];
    }
}

- (void)dealloc
{
    self.timeObserver = nil;
    self.audioPlayer = nil;
    audioRes = nil;
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
